package util.itext.pdf;

/**
 * Example written by Bruno Lowagie in answer to:
 * http://stackoverflow.com/questions/29092738/itext-chapter-title-and-columntext
 */

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CreateTOCinSideBar {

    public static final String SRC = "var/HelloCopy123.pdf";
    public static final String DEST = "tmp/HelloCopy123_with_sidebar_toc.pdf";

    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new CreateTOCinSideBar().createPdf(SRC, DEST);
    }

    public void createPdf(String src, String dest) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(src);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document(reader.getPageSizeWithRotation(1));
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));

        document.open();
        PdfOutline root = copy.getRootOutline();

        int pageCount = reader.getNumberOfPages();
        System.out.println("pageCount: " + pageCount);
        for (int i = 1; i <= pageCount; i++) {
            System.out.println("-----------" + i);
            newOutLine(root, i);
            copy.addPage(copy.getImportedPage(reader, i));
        }
        document.close();
    }

    private void newOutLine(PdfOutline root, int pageNum) {
        String text = "Page " + pageNum;
        PdfDestination dest = new PdfDestination(PdfDestination.XYZ, pageNum);
        new PdfOutline(root, dest, text);
    }

}
